package consul

import (
	"awesomeProject/goods-web/utils/register"
	"fmt"
	"github.com/hashicorp/consul/api"
	"go.uber.org/zap"
)

type Registry struct {
	Host string
	Port int
}

// 通过接口实现多态

func NewRegistryClient(host string, port int) register.RegistryClient {

	return &Registry{Host: host, Port: port}
}

func (r *Registry) Register(host string, port int, name string, tag []string, id string) error {
	// 初始化注册中心
	cfg := api.DefaultConfig()
	// 注意这里的参数应该是Consul对应的host和port
	cfg.Address = fmt.Sprintf("%s:%d", r.Host, r.Port) // consul的地址

	clientConsul, err := api.NewClient(cfg)
	if err != nil {
		panic(err)
	}

	check := &api.AgentServiceCheck{
		HTTP:                           fmt.Sprintf("http://%s:%d/health", host, port),
		Timeout:                        "5s",
		Interval:                       "60s",
		DeregisterCriticalServiceAfter: "10s",
	}

	registration := new(api.AgentServiceRegistration)
	registration.Name = name
	registration.ID = id
	registration.Port = port
	registration.Tags = tag
	registration.Address = host
	registration.Check = check

	if err := clientConsul.Agent().ServiceRegister(registration); err != nil {
		zap.S().Panic("服务注册失败")
		panic(err)
	}
	return nil
}
func (r *Registry) Deregister(serviceId string) error {
	// 初始化注册中心
	cfg := api.DefaultConfig()
	// 注意这里的参数应该是Consul对应的host和port
	cfg.Address = fmt.Sprintf("%s:%d", r.Host, r.Port) // consul的地址

	clientConsul, err := api.NewClient(cfg)
	if err != nil {
		return nil
	}
	// 进行服务注销
	return clientConsul.Agent().ServiceDeregister(serviceId)
}
